package com.example.service;

import cn.hutool.core.util.ObjectUtil;
import com.example.common.Constants;
import com.example.common.enums.ResultCodeEnum;
import com.example.common.enums.RoleEnum;
import com.example.entity.Account;
import com.example.entity.Admin;
import com.example.entity.PetShop;
import com.example.entity.User;
import com.example.exception.CustomException;
import com.example.mapper.AdminMapper;
import com.example.mapper.PetShopMapper;
import com.example.mapper.UserMapper;
import com.example.utils.CopyUtils;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 业务层方法
 */
@Service
public class UserService {

    @Resource
    private UserMapper userMapper;
    @Autowired
    private PetShopMapper petShopMapper;
    @Autowired
    private AdminMapper adminMapper;

    public void add(User user) {
        User dbUser = userMapper.selectByUsername(user.getUsername());
        if (ObjectUtil.isNotNull(dbUser)) {
            throw new CustomException(ResultCodeEnum.USER_EXIST_ERROR);
        }
        if (ObjectUtil.isEmpty(user.getPassword())) {
            user.setPassword(Constants.USER_DEFAULT_PASSWORD);
        }
        if (ObjectUtil.isEmpty(user.getName())) {
            user.setName(user.getUsername());
        }
        for (int i = 0; i < user.getRoleList().size(); i++) {
            if (ObjectUtil.equals(user.getRoleList().get(i), RoleEnum.PETSHOP.getValue()+"")) {
                PetShop petShopSelect = petShopMapper.selectByUsername(user.getUsername());
                if (ObjectUtil.isNull(petShopSelect)) {
                    PetShop petShop = new PetShop();
                    BeanUtils.copyProperties(user, petShop);
                    petShopMapper.insert(petShop);
                }
            }
            if (ObjectUtil.equals(user.getRoleList().get(i), RoleEnum.ADMIN.getValue()+"")) {
                Admin adminSelect = adminMapper.selectByUsername(user.getUsername());
                if (ObjectUtil.isNull(adminSelect)) {
                    Admin admin = new Admin();
                    BeanUtils.copyProperties(user, admin);
                    adminMapper.insert(admin);
                }
            }
        }
        user.setRole(RoleEnum.USER.name());
        userMapper.insert(user);
    }

    public void updateById(User user) {
        handleRole(user);
        userMapper.updateById(user);
    }

    public void deleteById(Integer id) {
        userMapper.deleteById(id);
    }

    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            userMapper.deleteById(id);
        }
    }

    public User selectById(Integer id) {
        return userMapper.selectById(id);
    }

    public List<User> selectAll(User user) {
        return userMapper.selectAll(user);
    }

    public PageInfo<User> selectPage(User user, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> list = userMapper.selectAll(user);
        for (int i = 0; i < list.size(); i++) {
            List<String> roleList = new ArrayList<>();
            PetShop petShop = petShopMapper.selectByUsername(list.get(i).getUsername());
            Admin admin = adminMapper.selectByUsername(list.get(i).getUsername());
            if (ObjectUtil.isNotNull(petShop)) {
                roleList.add(RoleEnum.PETSHOP.getValue()+"");
            }
            if (ObjectUtil.isNotNull(admin)) {
                roleList.add(RoleEnum.ADMIN.getValue()+"");
            }
            list.get(i).setRoleList(roleList);
        }
        return PageInfo.of(list);
    }

    /**
     * 登录
     */
    public User login(Account account) {
        User dbUser = userMapper.selectByUsername(account.getUsername());
        if (ObjectUtil.isNull(dbUser)) {
            throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
        }
        if (!dbUser.getPassword().equals(account.getPassword())) {
            throw new CustomException(ResultCodeEnum.USER_ACCOUNT_ERROR);
        }
        // 生成token
        String token = TokenUtils.createToken(dbUser.getId() + "-" + dbUser.getRole(), dbUser.getPassword());
        dbUser.setToken(token);
        return dbUser;
    }

    /**
     * 修改密码
     */
    public void updatePassword(Account account) {
        User dbUser = userMapper.selectByUsername(account.getUsername());
        if (ObjectUtil.isNull(dbUser)) {
            throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
        }
        if (!account.getPassword().equals(dbUser.getPassword())) {
            throw new CustomException(ResultCodeEnum.PARAM_PASSWORD_ERROR);
        }
        dbUser.setPassword(account.getNewPassword());
        userMapper.updateById(dbUser);
    }

    /**
     * 重置密码
     */
    public void resetPassword(Account account) {
        User dbUser = userMapper.selectById(account.getId());
        dbUser.setPassword(Constants.USER_DEFAULT_PASSWORD);
        userMapper.updateById(dbUser);
    }

    public void updateAccountById(Double price, Integer id) {
        userMapper.updateAccountById(price, id);
    }


    private void handleRole(User user) {
        List<String> roleList = user.getRoleList();
        List<Integer> hasRoleList = new ArrayList<>();
        Integer[] allRoleList = {RoleEnum.ADMIN.getValue(), RoleEnum.PETSHOP.getValue()};
        if (ObjectUtil.isNotEmpty(roleList)) {
            for (int i = 0; i < roleList.size(); i++) {
                String role = roleList.get(i);
                if (ObjectUtil.equals(role, RoleEnum.PETSHOP.getValue()+"")) {
                    // 查询是否存在
                    PetShop petShopSelect = petShopMapper.selectByUsername(user.getUsername());
                    if (ObjectUtil.isNull(petShopSelect)) {
                        // 如果不存在
                        PetShop petShop = new PetShop();
                        BeanUtils.copyProperties(user, petShop);
                        petShopMapper.insert(petShop);
                    }
                    hasRoleList.add(RoleEnum.PETSHOP.getValue());
                }
                if (ObjectUtil.equal(role, RoleEnum.ADMIN.getValue()+"")) {
                    Admin adminSelect = adminMapper.selectByUsername(user.getUsername());
                    if (ObjectUtil.isNull(adminSelect)) {
                        Admin admin = new Admin();
                        BeanUtils.copyProperties(user, admin);
                        adminMapper.insert(admin);
                    }
                    hasRoleList.add(RoleEnum.ADMIN.getValue());
                }
            }
        }
        for (int i = 0; i < hasRoleList.size(); i++) {
            Integer role = hasRoleList.get(i);
            for (int j = 0; j < allRoleList.length; j++) {
                if (ObjectUtil.equals(role, allRoleList[j])) {
                    allRoleList[j] = 9;
                }
            }
        }
        // 对于没有的删除
        for (int i = 0; i < allRoleList.length; i++) {
            if (allRoleList[i] != 9) {
                if (ObjectUtil.equals(allRoleList[i], RoleEnum.ADMIN.getValue())) {
                    adminMapper.deleteByUsername(user.getUsername());
                }
                if (ObjectUtil.equals(allRoleList[i], RoleEnum.PETSHOP.getValue())) {
                    petShopMapper.deleteByUsername(user.getUsername());
                }
            }
        }
    }

}
